package com.scalar.chiptrack.adaptor.msilica;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.adaptor.TestLot;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.XLSParserImpl;
import com.scalar.chiptrack.adaptor.dao.TestAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.InventoryLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Date;
import java.io.File;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 17 May, 2010
 * Time: 2:22:50 PM
 * To change this template use File | Settings | File Templates.
 */
public class MsilicaDataParser extends JobHandler implements AdaptorConstants
{
    private HashMap<String, TestLot> m_ftDataMap             = new HashMap<String, TestLot>();
    private HashMap<String, InventoryLot> m_fgDataMap        = new HashMap<String, InventoryLot>();

    private Logger m_parserLogger   = null;
    private String m_dataOutputDir  = null;

    public MsilicaDataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir(VENDOR_NAME_MSILICA, WIP_TYPE_TEST);
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_parserLogger = AdaptorUtils.getDataParserLogger( m_dataOutputDir,VENDOR_NAME_MSILICA );
            TestAdaptorDAO.setLogger( m_parserLogger );
            InventoryLotDAO.setLogger(m_parserLogger);
            AdaptorUtils.setLogger( m_parserLogger );
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading MSILICA Inventory output directory details from database, Exception: " + se);
            throw se;
        }
    }
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main( String args[] ) throws Exception
    {
        try
        {
            new MsilicaDataParser().execute();
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        AdaptorUtils.printHeader(VENDOR_NAME_MSILICA, CONSTANT_PARSER);

        File doneDestDir = new File(  m_dataOutputDir + "/done" );

        File sourceDataoutDir = new File( m_dataOutputDir );

        File[] fileList = sourceDataoutDir.listFiles();
        if ( ( fileList == null ) || ( fileList.length <= 3 ) )
        {
            log( "No file found in directory: " + sourceDataoutDir );
            throw new ScalarException( "\n+-----------No file found in directory " + sourceDataoutDir );
        }

        ArrayList<File> successFileList = new ArrayList<File>();

        boolean success = false;

        for ( int i = 0; i < fileList.length; i++ )
        {
            if ( fileList[i].isDirectory() == true )
            {
                continue;
            }

            try
            {
                // Step 1
                // Parse Files to get Object List
                if ( fileList[i].getName() != null && fileList[i].getName().trim().startsWith(MsilicaAdaptor.FILE_NAME_DAILY_WIP ) )
                {
                    parseInventoryReport( fileList[i].getAbsolutePath() );

                    successFileList.add( fileList[i] );
                }

                success = true;
            }
            catch ( Exception e )
            {
                success = false;
                log( "Exception while parsing and storing file: " + fileList[i].getAbsolutePath() + "\nException: " + e );
                e.printStackTrace();
                throw e;
            }
        }
        // Saving the Test Lot Information
        try
        {
            // Save Final Test Information
            if ( m_ftDataMap.isEmpty() == false )
            {
                log( " Updating Test Lot Information" );
                TestAdaptorDAO.saveTestLot( null, m_ftDataMap.values().iterator(), LOCATION_TYPE_FT, VENDOR_NAME_MSILICA );
            }
            else
            {
                TestAdaptorDAO.closeTestLot( null, LOCATION_TYPE_FT, VENDOR_NAME_MSILICA );
            }

            success = true;
            m_ftDataMap.clear();
            m_ftDataMap = null;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update Test Lot information into database: " + se );
            throw se;
        }

        // to save the FG lot tables
       try
       {
          if ( m_fgDataMap.isEmpty() == false )
          {
              log(" Updating Finshed Goods Lot Information");
              InventoryLotDAO.saveInventoryLot( null, m_fgDataMap.values().iterator(), LOCATION_TYPE_FG, VENDOR_NAME_MSILICA );
              success = true;
          }
          else
          {
              InventoryLotDAO.closeInventoryLot(null, LOCATION_TYPE_FG, VENDOR_NAME_MSILICA  );
          }
      }
      catch (ScalarException se)
      {
         success = false;
         se.printStackTrace();
         log("ERROR!! ERROR!! ERROR!! Could not update Finshed Goods Lot information into database: " + se);
         throw se;
      }

       // To Close the Drop Out Lots
        AdaptorDAO.closeDropOutLots(VENDOR_NAME_MSILICA);

         // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
        AdaptorDAO.sendAllNotifications(VENDOR_NAME_MSILICA, true, true, true);

       int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( MsilicaAdaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);

        // Update Adaptor_Run_Info table
        try
        {
            if ( success == true )
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, MsilicaAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }
        }
        catch ( ScalarException se )
        {
            success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, MsilicaAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
        }
        // Move the successful files to 'done' directory
       if ( success )
       {
           AdaptorUtils.moveFilesToDone( successFileList, doneDestDir );
       }
    }

    private void parseInventoryReport( String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result            = null;
        TestLot testLot         = null;
        InventoryLot inventoryLot = null;
        String lotNumber        = null;
        String partNumber       = null;
        String fablotNumber     = null;
        try
        {
            File detailWipFile = new File( fileName );
            if ( detailWipFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "\nParsing the file for Inventory Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for Inventory Report..." );

             Parser parser = ParserFactory.getXLSParser( detailWipFile );

            ((XLSParserImpl)parser).setHeaderRowIdx(0);
            ((XLSParserImpl)parser).setDataStartRowIdx(1);

            result = parser.parse();
            
            while ( result.next() )
            {
                partNumber = result.getString("Part Number");
                fablotNumber = result.getString("Lot Number");
                lotNumber   =  result.getString("Lot Number");
               
                if (partNumber!= null && partNumber.trim().length() >0 && lotNumber != null && lotNumber.trim().length() > 0 )
                {
                    // FT Process
                    if ( result.getString("STATUS") != null && "FT".equalsIgnoreCase( result.getString("STATUS") ) )
                    {
                        log(lotNumber + "In Test FT");

                        testLot = (TestLot) m_ftDataMap.get( partNumber + lotNumber + fablotNumber );
                        if (testLot == null)
                        {
                            testLot = new TestLot(VENDOR_NAME_MSILICA);
                            m_ftDataMap.put(partNumber + lotNumber + fablotNumber, testLot);
                        }

                       // FOR SETTING THE QTY IN
                        if( testLot.getQtyIn() != null )
                        {
                             try
                             {
                                 testLot.setQtyIn( ( Integer.parseInt( testLot.getQtyIn() ) + result.getInt("Qty Available") ) + "" );
                             }
                             catch(Exception e)
                             {
                                 testLot.setQtyIn( result.getInt("Qty Available")+"" );
                             }
                         }
                         else
                         {
                             testLot.setQtyIn( result.getInt("Qty Available")+"" );
                         }
                        if ( testLot.getStage() != null )
                         {
                            testLot.setStage( testLot.getStage() + "," + result.getString(9) );
                         }
                         else
                         {
                            testLot.setStage(result.getString(9));
                         }

                         if ( testLot.getQtyIn() != null && !"0".equalsIgnoreCase(testLot.getQtyIn() ) )
                         {
                            testLot.setPartNumber( partNumber );
                            testLot.setLotNumber( lotNumber );
                            testLot.setFabLotNumber( fablotNumber );

                            if ( result.getString("Date In") != null )
                            {
                                testLot.setDateIn( result.getString("Date In") );
                            }
                            testLot.setDateCode( result.getString("Date Code") );
                            testLot.setStatus(LOT_STATUS_RUNNING);
                            testLot.setPsType( LOCATION_TYPE_FT );
                            testLot.setCategory( LOT_CATEGORY_TYPE_PROD );

                        }
                    }

                    //FG Process
                    if( result.getString("STATUS") != null && "FG".equalsIgnoreCase( result.getString("STATUS") ) )
                    {
                        log( lotNumber + " In FG");
                        inventoryLot = (InventoryLot) m_fgDataMap.get( partNumber + lotNumber + fablotNumber );
                        if ( inventoryLot == null )
                        {
                            inventoryLot = new InventoryLot(VENDOR_NAME_MSILICA, LOCATION_TYPE_FG);
                            m_fgDataMap.put(partNumber + lotNumber + fablotNumber, inventoryLot);
                        }

                        if( inventoryLot.getQtyIn() != null )
                        {
                            try
                            {
                                inventoryLot.setQtyIn( ( Integer.parseInt( inventoryLot.getQtyIn() ) + result.getInt("Qty Available") ) + "" );
                            }
                            catch(Exception e)
                            {
                                inventoryLot.setQtyIn( result.getInt("Qty Available")+"" );
                            }
                         }
                         else
                         {
                            inventoryLot.setQtyIn( result.getInt("Qty Available")+"" );
                         }
                         if ( inventoryLot.getStage() != null )
                         {
                            inventoryLot.setStage( inventoryLot.getStage() + "," + result.getString(9));
                         }
                         else
                         {
                            inventoryLot.setStage(result.getString(9));
                         }

                         if ( inventoryLot.getQtyIn() != null && !"0".equalsIgnoreCase(inventoryLot.getQtyIn() ) )
                         {
                            inventoryLot.setPartNumber( partNumber );
                            inventoryLot.setLotNumber( lotNumber );
                            inventoryLot.setFabLotNumber( fablotNumber );

                            if ( result.getString("Date In") != null )
                            {
                                inventoryLot.setDateIn( result.getString("Date In") );
                            }
                            inventoryLot.setDateCode( result.getString("Date Code") );
                            inventoryLot.setStatus(LOT_STATUS_RUNNING);
                            inventoryLot.setCategory( LOT_CATEGORY_TYPE_PROD );
                        }
                    }

                } //Part number Null checking
            }
        }
        catch ( Exception ex )
        {
            System.out.println("ERROR!!!ERROR!!! While Parsing the Msilica Inventory Report");
            ex.printStackTrace();
            throw ex;
        }
    } // end of prase Turnkey Wip Report method


    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_parserLogger != null )
        {
            m_parserLogger.logDebug( message + LINE_SEPARATOR );
        }
        else
        {
            System.out.println( message );
        }
    } // end of log method
}
